if __name__ == '__main__':
    from notifier import Notifier
else:
    from .notifier import Notifier

from datetime import datetime
import winsound
import wave
import os
from io import BytesIO

class SoundNotifier(Notifier):

    def __init__(self,*args) -> None:
        super().__init__(*args)

    
    def notify(self):
        # audio_dir=os.path.join(os.path.dirname(__file__),'audio')
        # for pieces in self.get_sound_pieces():
        #     file=f'{audio_dir}/{pieces}.wav'
        #     flag=os.path.exists(file)
        #     winsound.PlaySound(file,winsound.SND_FILENAME)
        sound=self._merge_audio()
        winsound.PlaySound(sound.getvalue(),winsound.SND_MEMORY)
        sound.close()

    def get_sound_pieces(self):
        audio_pieces=[]
        audio_pieces.append('xianzaishi')
        time=datetime.now()
        hour=time.hour
        minute=time.minute
        audio_pieces.extend(self._map_int(hour))    
        audio_pieces.append('dian') 
        if minute==0:
            audio_pieces.append('zheng')
            return audio_pieces
        
        if minute==30:
            audio_pieces.append('ban')
            return audio_pieces

        audio_pieces.extend(self._map_int(minute))

        audio_pieces.append('fen')     
        return audio_pieces
    
    def _merge_audio(self):
        audio_dir=os.path.join(os.path.dirname(__file__),'audio','output')
        params=None
        frames=[]
        for pieces in self.get_sound_pieces():
            file=f'{audio_dir}/{pieces}.wav'
            # flag=os.path.exists(file)
            reader=wave.open(file,'rb')
            if not params:
                params=reader.getparams()
            frame_count=reader.getnframes()
            frames.append(reader.readframes(frame_count))
        
        merged=BytesIO()
        writer=wave.open(merged,'wb')
        writer.setparams(params)
        for data in frames:
            writer.writeframes(data)
        return merged

    
    def _map_int(self,i):
        res=[]
        if i<=10:
            res.append(str(i))
        elif i<20:
            res.append(str(10))
            res.append(str(i-10))
        else:
            res.append(str(i//10))
            res.append(str(10))
            if i%10:
                res.append(str(i%10))
        return res

if __name__ == '__main__':
    toast=SoundNotifier()
    toast.notify()
    # toast.notify_async()

